<template>
  <div class="slider-captcha">
    <div class="captcha-image-container" ref="imageContainer">
      <!-- 背景图片使用渐变色 -->
      <div class="background-gradient">
        <el-icon class="captcha-icon" :size="60">
          <component :is="icons[imageIndex]" />
        </el-icon>
      </div>
      
      <!-- 滑块使用小图标 -->
      <div class="slider-block" :style="blockStyle" v-show="isLoaded">
        <el-icon :size="20">
          <component :is="icons[imageIndex]" />
        </el-icon>
      </div>

      <!-- 遮罩层 -->
      <div class="mask" v-if="loading || verified">
        <el-icon v-if="loading"><Loading /></el-icon>
        <el-icon v-else-if="verified" class="success"><CircleCheck /></el-icon>
      </div>
    </div>

    <!-- 滑动条 -->
    <div class="slider-container" v-if="isLoaded">
      <div class="slider-track">
        <div class="slider-bar" :style="{ width: sliderLeft + 'px' }"></div>
        <div 
          class="slider-button"
          :class="{ 'is-moving': isDragging }"
          :style="{ left: sliderLeft + 'px' }"
          @mousedown="startDrag"
          @touchstart="startDrag">
          <el-icon v-if="!verified && !loading"><DArrowRight /></el-icon>
          <el-icon v-else-if="verified"><CircleCheck /></el-icon>
          <el-icon v-else><Loading /></el-icon>
        </div>
      </div>
      <div class="slider-text" :class="{ 'is-moving': isDragging }">
        {{ sliderText }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Picture, DArrowRight, CircleCheck, Loading } from '@element-plus/icons-vue'
import {
  Star, Bell, Calendar, ChatDotRound,
  Collection, CreditCard, Football, Goods, Grid
} from '@element-plus/icons-vue'

export default {
  name: 'SliderCaptcha',
  components: {
    Picture,
    DArrowRight,
    CircleCheck,
    Loading
  },
  props: {
    // 验证成功的回调
    onSuccess: {
      type: Function,
      default: () => {}
    },
    // 验证失败的回调
    onError: {
      type: Function,
      default: () => {}
    }
  },
  setup(props) {
    const imageContainer = ref(null)
    const isLoaded = ref(false)
    const isDragging = ref(false)
    const loading = ref(false)
    const verified = ref(false)
    const sliderLeft = ref(0)
    const startX = ref(0)
    const targetPosition = ref(0)

    // 随机生成验证码图片
    const imageIndex = ref(Math.floor(Math.random() * 10))
    const backgroundImage = computed(() => 
      `https://picsum.photos/320/160?random=${imageIndex.value}`
    )
    const blockImage = computed(() => 
      `https://picsum.photos/40/40?random=${imageIndex.value}`
    )

    // 滑块位置样式
    const blockStyle = computed(() => ({
      left: `${sliderLeft.value}px`,
      display: isLoaded.value ? 'block' : 'none'
    }))

    // 滑动条文字
    const sliderText = computed(() => {
      if (verified.value) return '验证通过'
      if (loading.value) return '验证中...'
      if (isDragging.value) return '拖动滑块完成拼图'
      return '向右拖动滑块完成拼图'
    })

    // 图片加载完成后初始化
    const onImageLoad = () => {
      if (!imageContainer.value) return
      const containerWidth = imageContainer.value.clientWidth
      // 随机生成目标位置（滑块最终应该在的位置）
      targetPosition.value = Math.floor(Math.random() * (containerWidth - 60) + 30)
      isLoaded.value = true
    }

    // 开始拖动
    const startDrag = (e) => {
      if (verified.value || loading.value) return
      isDragging.value = true
      startX.value = (e.type === 'mousedown' ? e.clientX : e.touches[0].clientX) - sliderLeft.value

      document.addEventListener('mousemove', onDrag)
      document.addEventListener('touchmove', onDrag)
      document.addEventListener('mouseup', stopDrag)
      document.addEventListener('touchend', stopDrag)
    }

    // 拖动中
    const onDrag = (e) => {
      if (!isDragging.value) return
      e.preventDefault()
      
      const currentX = e.type === 'mousemove' ? e.clientX : e.touches[0].clientX
      let newLeft = currentX - startX.value
      
      // 限制滑动范围
      const containerWidth = imageContainer.value.clientWidth
      newLeft = Math.max(0, Math.min(newLeft, containerWidth - 40))
      
      sliderLeft.value = newLeft
    }

    // 停止拖动
    const stopDrag = async () => {
      if (!isDragging.value) return
      isDragging.value = false
      loading.value = true

      // 验证位置是否正确（允许10px的误差）
      const isValid = Math.abs(sliderLeft.value - targetPosition.value) <= 10

      // 模拟验证过程
      await new Promise(resolve => setTimeout(resolve, 500))
      loading.value = false

      if (isValid) {
        verified.value = true
        props.onSuccess()
      } else {
        // 验证失败，重置位置
        sliderLeft.value = 0
        props.onError()
        // 重新生成验证码
        imageIndex.value = Math.floor(Math.random() * 10)
      }

      document.removeEventListener('mousemove', onDrag)
      document.removeEventListener('touchmove', onDrag)
      document.removeEventListener('mouseup', stopDrag)
      document.removeEventListener('touchend', stopDrag)
    }

    // 组件卸载时清理事件监听
    onUnmounted(() => {
      document.removeEventListener('mousemove', onDrag)
      document.removeEventListener('touchmove', onDrag)
      document.removeEventListener('mouseup', stopDrag)
      document.removeEventListener('touchend', stopDrag)
    })

    // 使用 Element Plus 图标
    const icons = [
      Picture, Star, Bell, Calendar, ChatDotRound,
      Collection, CreditCard, Football, Goods, Grid
    ]

    return {
      imageContainer,
      isLoaded,
      isDragging,
      loading,
      verified,
      sliderLeft,
      backgroundImage,
      blockImage,
      blockStyle,
      sliderText,
      onImageLoad,
      startDrag,
      icons
    }
  }
}
</script>

<style scoped>
.slider-captcha {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.captcha-image-container {
  position: relative;
  width: 100%;
  height: 160px;
  overflow: hidden;
}

.background-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.slider-block {
  position: absolute;
  top: 0;
  width: 40px;
  height: 40px;
  cursor: pointer;
  transition: left 0.1s;
}

.block-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.mask .el-icon {
  font-size: 32px;
  color: #fff;
}

.mask .success {
  color: #67C23A;
}

.slider-container {
  position: relative;
  height: 40px;
  background: #f5f7fa;
}

.slider-track {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}

.slider-bar {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background: #e1f3d8;
  transition: width 0.1s;
}

.slider-button {
  position: absolute;
  top: 0;
  width: 40px;
  height: 40px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  z-index: 2;
}

.slider-button:hover {
  background: #f5f7fa;
}

.slider-button.is-moving {
  background: #409EFF;
  border-color: #409EFF;
  color: #fff;
}

.slider-text {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  user-select: none;
}

.slider-text.is-moving {
  color: transparent;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
}

.image-error .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

@keyframes loading {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}

.el-icon.is-loading {
  animation: loading 1s linear infinite;
}

.background-gradient {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #1890ff 0%, #001529 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.captcha-icon {
  color: rgba(255, 255, 255, 0.2);
}

.slider-block {
  /* ... 其他样式保持不变 ... */
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
}

.slider-block .el-icon {
  color: #409EFF;
}
</style> 